<style scoped lang="scss">
.video-swiper-container {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
}

.video-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.video-item {
  width: 100vw;
  height: 100vh;
  flex-shrink: 0;
  background-color: $color-black;
  position: relative;

  .video-play-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); // 绝对居中
    width: 2rem; // 图标大小（根据需要调整）
    height: 2rem;
    background-color: rgba(0, 0, 0, 0.5); // 半透明背景
    border-radius: 50%; // 圆形背景
    z-index: 10; // 确保在视频上方
    cursor: pointer;

    // 绘制三角（通过border实现）
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 55%; // 三角稍微偏右，视觉居中
      transform: translate(-50%, -50%);
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 0.5rem 0 0.5rem 0.8rem; // 三角尺寸
      border-color: transparent transparent transparent white; // 白色三角
    }
  }

  .fast-control-toast {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    font-size: .6rem;
    padding: .2rem .6rem;
    border-radius: 1rem;
    z-index: 30;
    opacity: 0;
    transition: opacity 0.3s ease;

    &.show {
      opacity: 1;
    }
  }

  .text-wrap {
    position: absolute;
    left: 3%;
    bottom: 10%;
    color: $color-white;
    font-size: .6rem;
    font-weight: $font-weight-500;

    .geolocation {
      h6 {
        font-size: .3733rem;
        background-color: $color-login-btn;
        padding: 0 .1rem;
        border-radius: .08rem;
        @include flex-center;
        display: inline-block;
      }
    }

    .text-title {
      font-size: .4rem;
      margin-bottom: .2rem;
    }

    .text {
      width: 6.9867rem;
      max-height: 3rem;
      display: block;

      p {
        font-size: .3733rem;
      }
    }
  }

  .side-bar {
    position: absolute;
    width: 1.0667rem;
    height: 7.2rem;
    right: 3%;
    bottom: 9%;
    @include flex-center;
    flex-direction: column;

    .avatar {
      width: 1.0667rem;
      height: 1.0667rem;
      border-radius: 50%;
      position: relative;
      border: .05rem solid $color-white;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }

      .sum {
        width: .3rem;
        height: .3rem;
        border-radius: 50%;
        background-color: $color-red;
        @include flex-center;
        position: absolute;
        bottom: -.15rem;
        // 中间
        left: 50%;
        transform: translateX(-50%);

        i {
          font-size: .2rem;
          color: $color-white;
        }
      }
    }

    .publicBtn {
      @include flex-center;
      flex-direction: column;
      width: 1.0667rem;
      height: 1.4rem;
      margin-top: .4rem;
      color: $color-white;

      i {
        font-size: .8rem;
      }

      p {
        font-size: .3733rem;
      }
    }

    .like-btn-active {
      color: $color-red;
    }
  }

  .progress-container {
    position: absolute;
    bottom: 1.2rem;
    left: 0;
    width: 100%;
    height: .32rem; // 进度条高度
    padding: 0 .3rem; // 左右边距
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0.3); // 半透明背景
    display: flex;
    align-items: center;
    z-index: 20; // 确保在视频上方

    // 进度条轨道
    .progress-track {
      flex: 1;
      height: .04rem;
      background-color: rgba(255, 255, 255, 0.3); // 未播放部分颜色
      border-radius: .02rem;
      position: relative;
      cursor: pointer;

      // 已播放进度
      .progress-played {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        background-color: #face15; // 已播放部分颜色（黄色，和你的移动条一致）
        border-radius: .02rem;
        transition: width 0.1s linear;
      }

      // 进度条滑块
      .progress-thumb {
        position: absolute;
        top: 50%;
        width: .16rem;
        height: .16rem;
        background-color: #face15;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        box-shadow: 0 0 0 .04rem rgba(255, 255, 255, 0.3);
        transition: transform 0.1s ease;

        &:active {
          transform: translate(-50%, -50%) scale(1.2); // 点击时放大
        }
      }
    }

    // 时间显示（当前时间/总时长）
    .progress-time {
      margin-left: .2rem;
      color: white;
      font-size: .2667rem;
      min-width: 2rem; // 固定宽度避免抖动
      text-align: right;
    }
  }
}

.video-player {
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.back-btn {
  position: fixed;
  top: 3%;
  left: 3%;
  width: .8rem;
  height: .8rem;
  @include flex-center;
  color: $color-white;
  font-size: .6rem;
  z-index: 999;
  cursor: pointer;
}
</style>
<style lang="scss">
@keyframes commentSlideUp {
  from {
    opacity: 0;
    transform: translateX(100%);
  }

  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.commentSlideUp-enter-active {
  animation: commentSlideUp 0.3s ease-in-out !important;
}

@keyframes commentSlideDown {
  from {
    opacity: 1;
    transform: translateX(0);
  }

  to {
    opacity: 0;
    transform: translateX(100%);
  }
}

.commentSlideUp-leave-active {
  animation: commentSlideDown 0.3s ease-in-out !important;
}

.video-play-icon-hidden {
  display: none !important;
}
</style>

<template>
  <!-- 使用Teleport将评论组件挂载到body -->
  <CommentSection :showComment="showComment" :video="currentVideo" @close="isShowComment"
    @comment-success="commentSuccess" />

  <!-- 使用Transition包裹整个视频容器 -->
  <Transition name="commentSlideUp" mode="out-in">
    <!-- <teleport to="body" v-if="visible"> -->
    <div class="video-swiper-container" v-if="visible">
      <!-- 返回按钮 -->
      <div v-if="showBackButton" class="back-btn" @click="handleBack">
        <i class="iconfont icon-fanhui"></i>
      </div>

      <!-- 视频滑动区域 -->
      <div class="video-box" :style="{ transform: getTransform() }" :ref="setVideoBoxRef">
        <div class="video-item" v-for="(item, index) in processedVideoList" :key="item.videoId || index"
          @click.stop="playVideo(index)" @touchstart.passive="(e) => { touchStart(e); handleTouchStartFast(e, index); }"
          @touchmove.passive="touchMove($event)" @touchend="() => { touchEnd(); handleTouchEndFast(); }"
          @touchcancel="handleTouchEndFast">
          <div class="video-play-icon" :class="{ 'video-play-icon-hidden': !isVideoPaused[index] }">
          </div>
          <video :ref="(el) => setVideoRef(el, index)" class="video-player" playsinline webkit-playsinline
            @play="handleVideoPlay(index)" @pause="handleVideoPause(index)" @timeupdate="handleTimeUpdate(index)"
            @loadedmetadata="handleLoadedMetadata(index)">
            <source :src="item.video.videoPath" type="video/mp4">
          </video>
          <div class="progress-container">
            <div class="progress-track" @click="handleProgressClick($event, index)">
              <div class="progress-played" :style="{ width: `${progressPercent[index]}%` }"></div>
              <div class="progress-thumb" :style="{ left: `${progressPercent[index]}%` }"></div>
            </div>
            <div class="progress-time">
              {{ currentTime[index] }} / {{ duration[index] }}
            </div>
          </div>
          <!-- 快进快退提示 -->
          <div class="fast-control-toast" :class="{ show: fastControl.show && fastControl.index === index }">
            {{ fastControl.type === 'rewind' ? `快退 ${fastControl.speed}x` : `快进 ${fastControl.speed}x` }}
          </div>
          <div class="text-wrap">
            <!-- 地理信息 -->
            <div class="geolocation">
              <h6>{{ item.geolocation || '未知地点' }}</h6>
            </div>
            <div class="text-title">@{{ item.video.userNickname }}</div>
            <div class="text">
              <p>{{ item.video.videoDesc }}</p>
            </div>
          </div>

          <div class="side-bar">
            <!-- 头像 -->
            <div class="avatar" @click="handleProfileClick(item.video.userId)">
              <img :src="item.video.videoCover" alt="">
              <!-- 关注按钮 -->
              <div class="sum">
                <i class="iconfont icon-jia"></i>
              </div>
            </div>

            <!-- 点赞按钮 -->
            <div class="like-btn publicBtn">
              <i class="iconfont icon-aixin1" :class="{ 'like-btn-active': item.video.isLiked }"
                @click.stop="handleLike(item.video.videoId, videoList, videoItemKey, item)"></i>
              <p>{{ item.stats.likeNum }}</p>
            </div>

            <!-- 评论按钮 -->
            <div class="comment-btn publicBtn" @click.stop="handleOpenComment(item.video.videoId, item)">
              <i class="iconfont icon-pinglun"></i>
              <p>{{ item.stats.commentNum }}</p>
            </div>

            <!-- 分享按钮 -->
            <div class="share-btn publicBtn" @click.stop="handleShare(item.video.videoId)">
              <i class="iconfont icon-a-huaban1fuben37"></i>
              <p>{{ item.stats.shareNum }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- </teleport> -->
  </Transition>
</template>
<script setup>
import { useTemplateRef } from '../../hooks/useTemplateRef';
import { useTouchSwipe } from '../../hooks/useTouchSwipe';
import { useVideoStore } from '@/store/modules/video';
import CommentSection from '@/components/common/commentSection.vue';
import { useVideoPlayer } from '@/hooks/useVideoPlayer';
import { useVideoInteractions } from '@/hooks/useVideoInteractions';
import { computed } from 'vue';
import { useSocketInteractions } from '@/hooks/useSocketInteractions';
const { sendLike } = useSocketInteractions()

// Props定义
const props = defineProps({
  videoList: {
    type: Array,
    required: true,
    default: () => []
  },
  // 是否显示返回按钮
  showBackButton: {
    type: Boolean,
    default: true
  },
  // 返回按钮点击事件
  onBack: {
    type: Function,
    default: null
  },
  // 初始视频索引
  initialIndex: {
    type: Number,
    default: 0
  },
  // 是否启用滑动切换
  enableSwipe: {
    type: Boolean,
    default: true
  },
  // 是否自动播放
  autoPlay: {
    type: Boolean,
    default: true
  },
  // 过渡动画名称
  transitionName: {
    type: String,
    default: 'slide-up'
  },
  // 组件显示隐藏
  visible: {
    type: Boolean,
    default: true
  },
  // video小写和大写Video视频字符串
  videoItemKey: {
    type: String,
    default: 'video'
  },
  // 是否还有更多视频可加载
  hasMore: {
    type: Boolean,
    default: true
  },
});

// 事件定义
const emit = defineEmits([
  'back',
  'video-change',
  'like',
  'comment',
  'share',
  'play',
  'pause',
  'profile-click',
  'loadMore'
]);
const isLoadingMore = ref(false);
const processedVideoList = computed(() => {
  return props.videoList.map(item => {
    // 统一视频信息键名（video/Vidoe → video）
    const videoInfo = item.Video || item.video;
    // 统一统计数据键名（stats/WSLCNum → stats）
    const statsInfo = item.WSLCNum || item.stats;
    // 统一videoId（优先取item的videoId，没有则从视频信息中取）
    const videoId = item.videoId || (videoInfo?.videoId || '');

    return {
      ...item, // 保留其他原有属性
      video: videoInfo, // 统一为小写video
      stats: statsInfo, // 统一为stats
      videoId: videoId // 确保videoId存在
    };
  });
})
watch(
  () => props.initialIndex,
  (newIndex) => {
    console.log('初始索引变化:', newIndex);
    if (props.videoList.length > 0) {
      const validIndex = Math.min(Math.max(newIndex, 0), props.videoList.length - 1);
      setCurrentIndex(validIndex); // 触发 touchState.currentIndex 变化
      // 强制更新 DOM 偏移量（关键：让 getTransform 重新计算）
      if (videoBoxRef.value) {
        videoBoxRef.value.style.transform = getTransform();
      }
      // 若自动播放，重新播放目标视频
      if (props.autoPlay) {
        nextTick(() => {
          playCurrentVideo(validIndex);
        });
      }
    }
  },
  { immediate: true } // 初始化时立即触发
);
// 使用hooks
const { videoRefs, setVideoRef, toggleVideoPlay, pauseAllVideos } = useVideoPlayer();
const { showComment, currentVideo, commentVideoId, likeVideo, openComment } = useVideoInteractions();

const { templateRef: videoBoxRef, setTemplateRef: setVideoBoxRef } = useTemplateRef();

// 计算最大索引
const maxIndex = computed(() => {
  return props.videoList.length > 0 ? props.videoList.length - 1 : 0;
});

// 使用触摸滑动hook
const { start, move, end, getTransform, setCurrentIndex, currentIndex } = useTouchSwipe({
  threshold: 0.15,
  maxIndex: maxIndex,
  onIndexChange: (newIndex) => {
    playCurrentVideo(newIndex);
    emit('video-change', newIndex, props.videoList[newIndex]);
  }
});

// 播放当前视频
const playCurrentVideo = (targetIndex) => {
  if (!props.autoPlay) return;

  videoRefs.value.forEach((video, index) => {
    if (video && index !== targetIndex) {
      video.pause();
      emit('pause', index, props.videoList[index]);
    } else if (video && index === targetIndex) {
      // 切换到当前视频时，确保进度条从正确位置开始
      nextTick(() => {
        handleTimeUpdate(targetIndex);
      });
    }
  });

  const targetVideo = videoRefs.value[targetIndex];
  if (targetVideo) {
    targetVideo.play().catch(err => {
      console.warn('视频自动播放失败（需用户先交互）', err);
    });
    emit('play', targetIndex, props.videoList[targetIndex]);
  }
};

// 点击播放/暂停
const playVideo = (index) => {
  handleTouchEndFast();

  const currentVideo = videoRefs.value[index];
  if (currentVideo) {
    if (currentVideo.paused) {
      currentVideo.play();
      emit('play', index, props.videoList[index]);
    } else {
      currentVideo.pause();
      emit('pause', index, props.videoList[index]);
    }
  }
};
const isVideoPaused = ref([]);
watch(() => processedVideoList.value.length, (newLength) => {
  isVideoPaused.value = Array(newLength).fill(true); // 初始都暂停
});
// 处理视频播放事件
const handleVideoPlay = (index) => {
  console.log('视频播放:', index);
  isVideoPaused.value[index] = false;
};

// 处理视频暂停事件
const handleVideoPause = (index) => {
  console.log('视频暂停:', index);
  isVideoPaused.value[index] = true;
};
// 视频进度条逻辑
const progressPercent = ref([]); // 每个视频的进度百分比（0-100）
const currentTime = ref([]); // 每个视频的当前播放时间（秒）
const duration = ref([]); // 每个视频的总时长（秒）

watch(() => processedVideoList.value.length, (newLength) => {
  progressPercent.value = Array(newLength).fill(0);
  currentTime.value = Array(newLength).fill(0);
  duration.value = Array(newLength).fill(0);
});
const handleLoadedMetadata = (index) => {
  const video = videoRefs.value[index];
  if (video) {
    // 保留两位小数
    duration.value[index] = Number(video.duration.toFixed(2)); // 总时长（秒）
  }
};
const handleTimeUpdate = (index) => {
  const video = videoRefs.value[index];
  if (video && duration.value[index] > 0) {
    // 保留两位小数
    currentTime.value[index] = Number(video.currentTime.toFixed(2)); // 当前播放时间
    // 计算进度百分比（避免超过100%）
    progressPercent.value[index] = Math.min((currentTime.value[index] / duration.value[index]) * 100, 100);
  }
};
// 点击进度条跳转视频播放位置
const handleProgressClick = (event, index) => {
  handleTouchEndFast(); // 新增：点击进度条时停止快进快退

  const video = videoRefs.value[index];
  if (!video || duration.value[index] === 0) return;

  const track = event.currentTarget;
  const rect = track.getBoundingClientRect();
  const clickX = event.clientX - rect.left;
  const ratio = clickX / rect.width;
  const jumpTime = ratio * duration.value[index];

  video.currentTime = jumpTime;
  currentTime.value[index] = jumpTime;
  progressPercent.value[index] = ratio * 100;
  playVideo(index);
};

// 快进快退逻辑实现
const fastControl = ref({
  show: false, // 是否显示快进/快退提示
  type: 'rewind', // 类型：rewind（快退）/ forward（快进）
  index: -1, // 当前操作的视频索引
  speed: 2, // 快进/快退速度（单位：秒/次）
  timer: null, // 定时器（用于持续更新进度）
  isLongPress: false, // 是否处于长按状态
  startTime: 0 // 记录长按开始时间
});
const handleTouchStartFast = (e, index) => {
  const video = videoRefs.value[index];
  if (
    !video ||
    duration.value[index] === 0 ||
    index >= currentTime.value.length ||
    index >= progressPercent.value.length
  ) {
    return;
  }


  // 区分左右区域（左50%快退，右50%快进）
  const screenWidth = document.documentElement.clientWidth;
  const touchX = e.touches[0].clientX;
  const isLeft = touchX < screenWidth / 2;

  // 标记长按状态
  fastControl.value = {
    show: false, // 初始隐藏
    type: isLeft ? 'rewind' : 'forward',
    index,
    speed: 2,
    timer: null,
    isLongPress: true,
    startTime: Date.now() // 记录长按开始时间
  };
  // 延迟触发（避免误触，如点击播放）
  const timer = setTimeout(() => {
    if (
      fastControl.value.isLongPress &&
      Date.now() - fastControl.value.startTime >= 500 &&
      fastControl.value.index === index
    ) {
      fastControl.value.show = true; // 此时再显示提示
      fastControl.value.timer = setInterval(() => {
        updateVideoProgress(index, fastControl.value.type);
      }, 100);
    } else {
      // 长按不足2秒：隐藏提示
      fastControl.value.show = false;
    }
  }, 500);
  // 记录定时器ID，用于后续清除
  fastControl.value.timerId = timer;
};

// 新增：更新视频进度（快进/快退核心）
const updateVideoProgress = (index, type) => {
  const video = videoRefs.value[index];
  // 完整校验：避免报错
  if (
    !video ||
    index >= currentTime.value.length ||
    index >= progressPercent.value.length ||
    duration.value[index] === 0
  ) {
    handleTouchEndFast();
    return;
  }

  const currentTimeVal = video.currentTime; // 避免覆盖响应式变量
  const totalDuration = duration.value[index];
  const step = fastControl.value.speed * 0.1; // 每100ms移动0.2秒

  let newTime;
  if (type === 'rewind') {
    newTime = Math.max(currentTimeVal - step, 0); // 快退不小于0
  } else {
    newTime = Math.min(currentTimeVal + step, totalDuration); // 快进不大于总时长
  }

  // 更新视频进度 + 同步进度条
  video.currentTime = newTime;
  currentTime.value[index] = Number(newTime.toFixed(2));
  progressPercent.value[index] = Math.min((newTime / totalDuration) * 100, 100);
};
const handleTouchEndFast = () => {
  // 清除快进快退定时器
  if (fastControl.value.timer) {
    clearInterval(fastControl.value.timer);
  }
  // 2. 清除延迟触发定时器（关键！避免内存泄漏）
  if (fastControl.value.timeoutTimer) {
    clearTimeout(fastControl.value.timeoutTimer);
  }
  // 3. 重置所有状态
  fastControl.value = {
    show: false,
    type: 'rewind',
    index: -1,
    speed: 2,
    timer: null,
    timeoutTimer: null,
    isLongPress: false,
    startTime: 0
  };
};

// 处理返回按钮
const handleBack = () => {
  emit('back');
};

// 处理点赞
const handleLike = (videoId, videoList, type, item) => {
  console.log('item:', type);
  let userId = null
  if (type === 'video') {
    userId = item.video.userId
  } else {
    userId = item.Video.userId
  }
  if (!userId) return
  sendLike({
    toUserId: userId
  })
  likeVideo(videoId, videoList, type);
  emit('like', videoId);
};

// 处理打开评论
const handleOpenComment = (videoId, item) => {
  openComment(videoId);
  emit('comment', videoId);
};

// 处理分享
const handleShare = (videoId) => {
  emit('share', videoId);
};

// 触摸事件处理
const touchStart = (e) => {
  if (!props.enableSwipe) return;
  start(e);
  if (videoBoxRef.value) videoBoxRef.value.style.transition = 'none';
};

const touchMove = (e) => {
  if (!props.enableSwipe) return;

  // 滑动时立即停止快进快退（避免冲突）
  if (fastControl.value.isLongPress) {
    handleTouchEndFast();
  }

  move(e);
};

const touchEnd = (e) => {
  if (!props.enableSwipe) return;
  const prevIndex = currentIndex.value;
  console.log('prevIndex:', prevIndex);

  end(e);
  if (videoBoxRef.value) {
    videoBoxRef.value.style.transition = 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
  }
  const lastVideoIndex = props.videoList.length - 1;
  const hasMore = props.hasMore;
  // 检查是否滑动到下一个视频且有更多视频可加载
  console.log('currentIndex:', currentIndex.value);

  if (
    currentIndex.value === lastVideoIndex &&
    hasMore &&
    !isLoadingMore.value
  ) {
    isLoadingMore.value = true; // 标记为加载中
    emit('loadMore'); // 通知父组件加载更多
  } else {
    console.log('没有更多视频可加载');
  }
};

// 关闭评论
const isShowComment = () => {
  showComment.value = false;
};

// 评论成功回调
const commentSuccess = () => {
  openComment();
};

// 监听外部暂停指令
const videoStore = useVideoStore();
watch(() => videoStore.shouldPause, (newValue) => {
  if (newValue) {
    pauseAllVideos();
  }
});

// 初始化当前索引
onMounted(() => {
  nextTick(() => { // 等待 videoList 渲染完成
    if (props.videoList.length > 0) {
      const validIndex = Math.min(
        Math.max(props.initialIndex, 0),
        props.videoList.length - 1
      );
      setCurrentIndex(validIndex);
      // 手动触发一次 transform 更新
      if (videoBoxRef.value) {
        videoBoxRef.value.style.transform = getTransform();
      }
      if (props.autoPlay) {
        playCurrentVideo(validIndex);
      }
    }
  });
});
watch(
  () => props.videoList.length,
  (newLength, oldLength) => {
    if (newLength > oldLength) {
      isLoadingMore.value = false;
    }
    // 当视频列表变化后，确保当前索引仍在有效范围内
    if (newLength > 0) {
      const validIndex = Math.min(currentIndex.value, newLength - 1);
      if (validIndex !== currentIndex.value) {
        setCurrentIndex(validIndex);
      }
    }
  }
);
// 处理点击头像
const handleProfileClick = (userId) => {
  emit('profile-click', userId);
};
// 暴露给父组件的方法
defineExpose({
  pauseAllVideos,
  playVideo: (index) => playCurrentVideo(index),
  getCurrentIndex: () => currentIndex.value,
  setCurrentIndex
});
</script>